package cn.com.xiaoshoujia.activities.activity;

import cn.com.xiaoshoujia.activities.dto.*;
import cn.com.xiaoshoujia.activities.entity.Activity;
import cn.com.xiaoshoujia.activities.entity.ActivityRules;
import cn.com.xiaoshoujia.activities.exception.ActivityException;
import cn.com.xiaoshoujia.activities.mapper.ActivityMapper;
import cn.com.xiaoshoujia.activities.mapper.ActivityRulesMapper;
import cn.com.xiaoshoujia.activities.vo.ActivityDetailSiteVO;
import cn.com.xiaoshoujia.activities.vo.ActivitySiteVO;
import cn.com.xiaoshoujia.activities.vo.ActivityWxVO;
import cn.com.xiaoshoujia.application.service.FileUploadService;
import cn.com.xiaoshoujia.common.entity.City;
import cn.com.xiaoshoujia.common.mapper.CityMapper;
import cn.com.xiaoshoujia.company.entity.CompanyUser;
import cn.com.xiaoshoujia.company.mapper.CompanyUserMapper;
import cn.com.xiaoshoujia.order.activity.OrderActivity;
import cn.com.xiaoshoujia.order.entity.ActivityOrder;
import cn.com.xiaoshoujia.order.mapper.ActivityOrderMapper;
import cn.com.xiaoshoujia.quartz.site.ActivityQuartz;
import cn.com.xiaoshoujia.user.entity.ActivityTeamHead;
import cn.com.xiaoshoujia.user.mapper.ActivityJoinMapper;
import cn.com.xiaoshoujia.user.mapper.ActivityTeamHeadMapper;
import cn.com.xiaoshoujia.utils.DateUtils;
import cn.com.xiaoshoujia.utils.QueryResult;
import cn.com.xiaoshoujia.utils.SerializationUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Repository
public class ActivitiesActivity {

    private Logger logger = LoggerFactory.getLogger(OrderActivity.class);

    @Resource(name = "schedulerFactoryBean")
    private Scheduler scheduler;

    public static String dateFormate = "ss mm HH dd MM ? yyyy";
    public static SimpleDateFormat cronSdf = new SimpleDateFormat(dateFormate);

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityRulesMapper activityRulesMapper;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private ActivityJoinMapper activityJoinMapper;

    @Autowired
    private ActivityTeamHeadMapper activityTeamHeadMapper;

    @Autowired
    private ActivityOrderMapper activityOrderMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;


    /*--------------------site start--------------------*/

    /**
     * @Author: yangrui
     * @Description: 发布拼团
     * @Date: 上午11:24 2017/7/27
     */
    @Transactional
    public boolean saveTeamActivity(ActivitySiteDTO activitySiteDTO) {
        String name = String.valueOf(System.currentTimeMillis());
        String jobName = "activityJob" + name;

        Date date = new Date();
        Activity activity = new Activity();
        activity.setCreateTime(date);
        activity.setJobName(jobName);
        BeanUtils.copyProperties(activitySiteDTO, activity);
        int i = activityMapper.save(activity);
        if (i > 0) {
            ActivityRules activityRules = new ActivityRules();
            activityRules.setFkActivitiesId(activity.getId());
            BeanUtils.copyProperties(activitySiteDTO, activityRules);
            i = activityRulesMapper.save(activityRules);
        }
        if (i > 0) {
            /*定时器 start*/
            logger.info("team site quartz");

            String triggerName = "activityTrigger" + name;
            logger.info("team site quartz jobName {}", jobName);
            logger.info("team site quartz triggerName {}", triggerName);
            Long id = activity.getId();
            logger.info("team site quartz id {}", id);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date1 = null;
            try {
                date1 = sdf.parse(activitySiteDTO.getEndTime());
            } catch (ParseException e1) {
                throw new ActivityException("日期格式有误");
            }

//            int hour = 600;  //测试10分
            JobKey jobKey = JobKey.jobKey(jobName, "activityGroup");
            JobDetail job = JobBuilder.newJob(ActivityQuartz.class).withIdentity(jobKey).usingJobData("jobName", jobName).usingJobData("id", id).build();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date1);
//            rightNow.setTime(date);
            /*测试*/
//            rightNow.add(Calendar.SECOND, hour);//日期加10分
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, "activityGroup")
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronSdf.format(rightNow.getTime())))
                    .build();
            try {
                scheduler.scheduleJob(job, trigger);
                scheduler.start();
                logger.info("team site quartz start");
            } catch (SchedulerException e) {
                logger.error("team site quartz error {}", e.toString());
            }
            /*定时器 end*/
        }
        return i > 0;
    }


    /**
     * @Author: yangrui
     * @Description: 分页显示拼团信息
     * @Date: 下午2:02 2017/7/28
     */
    public QueryResult findByPage(ActivitySiteVO activitySiteVO) {
        QueryResult queryResult = new QueryResult();
        Long totalSize = activityMapper.findCount(activitySiteVO);
        List list = activityMapper.findByPage(activitySiteVO);
        if (list != null && list.size() > 0) {
            list.stream().forEach(object -> {
                ActivitySiteVO vo = (ActivitySiteVO) object;
                if (vo.getEndTime() != null) {
                    boolean aBoolean = vo.getEndTime().getTime() < new Date().getTime();
                    if (aBoolean) {
                        vo.setOverTime("1");
                    } else {
                        vo.setOverTime("0");
                    }
                }
            });
        }
        Long totalPage = totalSize % activitySiteVO.getPageSize() == 0 ? totalSize / activitySiteVO.getPageSize() : totalSize / activitySiteVO.getPageSize() + 1;
        queryResult.setTotalPage(totalPage);
        queryResult.setTotalSize(totalSize);
        queryResult.setList(list);
        return queryResult;
    }

    /**
     * @Author: yangrui
     * @Description: 修改状态，0 进行中，1 暂停
     * @Date: 下午4:09 2017/7/28
     */
    public boolean updateStatus(Activity activity) {
        return activityMapper.updateStatus(activity) > 0;
    }

    /**
     * @Author: yangrui
     * @Description: 根据拼团唯一ID查询信息
     * @Date: 下午4:33 2017/7/31
     */
    public ActivityDetailSiteVO findById(Long id) {
        ActivityDetailSiteVO activitySiteDTO = (ActivityDetailSiteVO) activityMapper.findById(id);
        if (activitySiteDTO == null) {
            throw new ActivityException("该拼团不存在");
        }
        boolean aBoolean = activitySiteDTO.getActivitiesStatus() != null && activitySiteDTO.getActivitiesStatus() == 0;
        if (aBoolean) {
            throw new ActivityException("该拼团还在进行中，请先暂停");
        }
        if (activitySiteDTO.getCityId() != null) {
            Long cityId = Long.valueOf(activitySiteDTO.getCityId());
            City city = cityMapper.findByCityId(cityId);
            if (city != null) {
                if (city.getParentId() != 0) {
                    City city1 = cityMapper.findByCityId(city.getParentId());
                    if (city1 != null) {
                        activitySiteDTO.setFirstCityId(city1.getCityId());
                    }
                    activitySiteDTO.setSecondCityId(city.getCityId());
                }
            }
        }
        if (!StringUtils.isEmpty(activitySiteDTO.getStartTime())) {
            activitySiteDTO.setStartTime(DateUtils.date2TimeStamp(activitySiteDTO.getStartTime()));
        }
        if (!StringUtils.isEmpty(activitySiteDTO.getEndTime())) {
            activitySiteDTO.setEndTime(DateUtils.date2TimeStamp(activitySiteDTO.getEndTime()));
        }
        if (!"-1".equals(activitySiteDTO.getPicture())) {
            activitySiteDTO.setPictureUrl(fileUploadService.getResourceUrlNoExpires(Long.valueOf(activitySiteDTO.getPicture())));
        } else {
            activitySiteDTO.setPictureUrl("http://topsales.oss-cn-beijing.aliyuncs.com/other/2.png");
        }
        if (!StringUtils.isEmpty(activitySiteDTO.getDetail())) {
            activitySiteDTO.setDetailurl(fileUploadService.getResourceUrlNoExpires(Long.valueOf(activitySiteDTO.getDetail())));
        }
        return activitySiteDTO;
    }

    /**
     * @Author: yangrui
     * @Description: 逻辑删除
     * @Date: 下午6:21 2017/7/31
     */
    public boolean delete(Activity activity) {
        return activityMapper.delete(activity) > 0;
    }

    @Transactional
    public boolean update(Activity activity, ActivityRules activityRules) {
        String jn = activityMapper.findJobNameById(activity.getId());

        String name = String.valueOf(System.currentTimeMillis());
        String jobName = "activityJob" + name;

        Date date = new Date();
        activity.setMendTime(date);
        activity.setJobName(jobName);
        int i = activityMapper.update(activity);
        if (i > 0) {
            i = activityRulesMapper.update(activityRules);
            if (i > 0) {
                /*定时器 start*/
                logger.info("team site update quartz");
                String triggerName = "activityTrigger" + name;
                logger.info("team site update quartz triggerName {}", triggerName);
                Long id = activity.getId();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date1 = null;
                try {
                    date1 = sdf.parse(activity.getEndTime());
                } catch (ParseException e1) {
                    throw new ActivityException("日期格式有误");
                }

                JobKey jobKey1 = JobKey.jobKey(jobName, "activityGroup");
                JobDetail job = JobBuilder.newJob(ActivityQuartz.class).withIdentity(jobKey1).usingJobData("id", id).build();
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(date1);

                Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, "activityGroup")
                        .withSchedule(CronScheduleBuilder.cronSchedule(cronSdf.format(rightNow.getTime())))
                        .build();
                try {
                    if (!StringUtils.isEmpty(jn)) {
                        JobKey jobKey = JobKey.jobKey(jn, "activityGroup");
                        scheduler.deleteJob(jobKey);
                    }
                    scheduler.scheduleJob(job, trigger);
                    scheduler.start();
                } catch (SchedulerException e) {
                    logger.error("team site quartz update error {}", e.toString());
                }
                /*定时器 end*/
            }
        }
        if (i == 0) {
            throw new RuntimeException("系统异常");
        }
        return i > 0;
    }
    /*--------------------site end--------------------*/

    /**
     * @Author: dulei
     * @Description: 获得向C端发送短信信息
     * @param: id 活动ID
     * @Date: 2017/7/30 22:09
     */
    public ActivitySmsMsgDTO findCSmsMsg(Long id) {
        ActivitySmsMsgDTO smsMsg = (ActivitySmsMsgDTO) activityMapper.findCSmsMsg(id);
        String[] strs = SerializationUtils.getJsonArrStrFormStrings(smsMsg.getPhone());
        if (null != strs)
            smsMsg.setPhone(StringUtils.join(strs, ","));
        else
            smsMsg.setPhone("--");
        return smsMsg;
    }

    /**
     * @Author: dulei
     * @Description: 查询拼团活动集合
     * @param: xcode 企业唯一编码
     * @Date: 2017/8/2 14:25
     */
    public List<ActivityDTO> listTeam(String xcode, Long id) {
        logger.info("start get activityList xcode = {} ,id = {}", xcode, id);
        List<ActivityDTO> list = activityMapper.listTeamByXcode(xcode);
        if (null != id) {
            Activity activity = (Activity) activityMapper.findActivityById(id);
            if (null != activity) {
                if (activity.getActivitiesStatus().intValue() == 1 && activity.getStatus().intValue() == 1) {
                    ActivityDTO activityDTO = new ActivityDTO();
                    BeanUtils.copyProperties(activity, activityDTO);
                    if (null==list)
                        list = new ArrayList<>();
                    list.add(activityDTO);
                }
            } else
                logger.error("参数错误 id = {}", id);
        }
        return list;
    }

    /*--------------------wx start--------------------*/
    public Activity findWxStatusById(Long id) {
        return activityMapper.findWxStatusById(id);
    }

    /*--------------------wx end--------------------*/

    /*--------------------wx start--------------------*/

    /**
     * @Author: dulei
     * @Description: 查找拼团活动信息1
     * @param: id 拼团活动ID
     * @Date: 2017/8/3 14:13
     */
    public ActivityWxTeamMsgDTO findWxActivityMsg(Long id) {
        ActivityWxTeamMsgDTO wxTeamMsg = new ActivityWxTeamMsgDTO();
        ActivityWxVO wxDetail = activityMapper.findWxDetailById(id);
        BeanUtils.copyProperties(wxDetail, wxTeamMsg);
        CompanyUser companyUser = companyUserMapper.findByXcode(wxDetail.getFkCompanyXcode());
        if (null != companyUser) {
            wxTeamMsg.setBindState(companyUser.getBindState());
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (wxDetail.getCityId() != null) {
            City city = cityMapper.findByCityId(wxDetail.getCityId());
            if (city != null) {
                if (city.getParentId() != 0) {
                    City city1 = cityMapper.findByCityId(city.getParentId());
                    if (city1 != null) {
                        stringBuffer.append(city1.getCityName());
                    }
                }
                stringBuffer.append(city.getCityName());
            }
        }
        wxTeamMsg.setAddress(stringBuffer.append(wxDetail.getAddress()).toString());

        if (null != wxDetail.getPicture() && wxDetail.getPicture().intValue() != -1) {
            wxTeamMsg.setPicture(fileUploadService.getResourceUrlNoExpires(wxDetail.getPicture()));
        } else {
            wxTeamMsg.setPicture("http://topsales.oss-cn-beijing.aliyuncs.com/other/2.png");
        }
        if (null != wxDetail.getDetail() && wxDetail.getDetail().intValue() != -1) {
            wxTeamMsg.setDetail(fileUploadService.getResourceUrlNoExpires(wxDetail.getDetail()));
        }
        if (wxDetail.getStatus() == 0)
            wxTeamMsg.setActivitiesStatus(-1);
        else {
            Date date = new Date();
            if (date.compareTo(wxTeamMsg.getEndTime()) >= 0) {
                wxTeamMsg.setActivitiesStatus(2);
            }
        }
        return wxTeamMsg;
    }

    /**
     * @Author: dulei
     * @Description: 只提供拼团活动状态等信息1  8-9 不用
     * @param: id 拼团活动ID
     * @Date: 2017/8/3 17:21
     */
    public ActivityWxVO findActivityStatus(Long id) {
        return activityMapper.findActivityStatus(id);
    }

    /**
     * @Author: dulei
     * @Description: 提供用户订单及参团信息1  8-9 不用
     * @param: sysId 用户openId id 拼团活动ID
     * @Date: 2017/8/3 17:21
     */
    public ActivityWxJoinStatusDTO findJoinStatus(String sysId, Long id) {
        ActivityWxJoinStatusDTO activityWxJoinStatusDTO = new ActivityWxJoinStatusDTO();
        ActivityWxJoinStatusDTO joinStatus = (ActivityWxJoinStatusDTO) activityJoinMapper.findJoinStatus(sysId, id);
        if (null != joinStatus)
            BeanUtils.copyProperties(joinStatus, activityWxJoinStatusDTO);
        ActivityOrder activityOrder = activityOrderMapper.findSingleStatus(sysId, id);
        if (null != activityOrder)
            activityWxJoinStatusDTO.setSingleStatus(activityOrder.getStatus());
        return activityWxJoinStatusDTO;
    }

    /**
     * @Author: dulei
     * @Description: 提供上级分享者团状态信息1 8-9 不用
     * @param: parentId 上级分享者信息 拼团活动ID
     * @Date: 2017/8/3 17:22
     */
    public Integer findShareStatus(Long parentId, Long id) {
        String shareId = activityJoinMapper.findShareId(parentId);
        return activityJoinMapper.findShareStatus(shareId, id);
    }

    /**
     * @Author: dulei
     * @Description: 查询活动表单信息及返回团状态及活动状态信息
     * @param: * @param null
     * @Date: 2017/8/4 10:16
     */
    public ActivityOperationJsonDTO findOperaionJson(Long id, Long headId) {
        ActivityOperationJsonDTO operaionJson = (ActivityOperationJsonDTO) activityMapper.findOperaionJson(id, headId);
        if (operaionJson.getStatus().intValue() == 0)
            operaionJson.setActivitiesStatus(-1);
        return operaionJson;
    }

    public ActivityWxActivityMsgDTO findTeamAndHead(Long id, Long headId) {
        ActivityWxActivityMsgDTO wxTeamMsg = new ActivityWxActivityMsgDTO();
        ActivityWxVO wxDetail = activityMapper.findWxDetailById(id);
        BeanUtils.copyProperties(wxDetail, wxTeamMsg);
        StringBuffer stringBuffer = new StringBuffer();
        if (wxDetail.getCityId() != null) {
            City city = cityMapper.findByCityId(wxDetail.getCityId());
            if (city != null) {
                if (city.getParentId() != 0) {
                    City city1 = cityMapper.findByCityId(city.getParentId());
                    if (city1 != null) {
                        stringBuffer.append(city1.getCityName());
                    }
                }
                stringBuffer.append(city.getCityName());
            }
        }
        wxTeamMsg.setAddress(stringBuffer.append(wxDetail.getAddress()).toString());
        if (null != wxDetail.getPicture() && wxDetail.getPicture().intValue() != -1) {
            wxTeamMsg.setPicture(fileUploadService.getResourceUrlNoExpires(wxDetail.getPicture()));
        } else {
            wxTeamMsg.setPicture("http://topsales.oss-cn-beijing.aliyuncs.com/other/2.png");
        }
        if (wxDetail.getStatus() == 0)
            wxTeamMsg.setActivitiesStatus(-1);
        if (null != headId) {
            ActivityTeamHead wxHeadById = activityTeamHeadMapper.findWxHeadById(headId);
            wxTeamMsg.setTeamStatus(wxHeadById.getStatus());
            wxTeamMsg.setTeamTime(wxHeadById.getFinishTime());
        }
        return wxTeamMsg;
    }
    /*--------------------site end--------------------*/

    /*--------------------wx start--------------------*/

    public ActivityTeamHead findWxHeadById(Long headId) {
        return activityTeamHeadMapper.findWxHeadById(headId);
    }

    public ActivitySuccessDTO findSuccessMsg(Long id, Long headId) {
        ActivitySuccessDTO activitySuccessDTO = (ActivitySuccessDTO) activityMapper.findActivityMsg(id);
        if (null != activitySuccessDTO) {
            if (StringUtils.isNotBlank(activitySuccessDTO.getPicture()) && !"-1".equals(activitySuccessDTO.getPicture())) {
                activitySuccessDTO.setPicture(fileUploadService.getResourceUrlNoExpires(Long.valueOf(activitySuccessDTO.getPicture())));
            } else {
                activitySuccessDTO.setPicture("http://topsales.oss-cn-beijing.aliyuncs.com/other/2.png");
            }
            if (null != headId) {
                ActivityTeamHead head = activityTeamHeadMapper.findHeadById(headId);
                activitySuccessDTO.setEndTime(org.apache.commons.lang.time.DateUtils.addHours(head.getPayTime(), activitySuccessDTO.getTimeLimit()));
                Integer successCount = activityOrderMapper.findSuccessCount(headId);
                activitySuccessDTO.setCount(activitySuccessDTO.getParticipants().intValue() - successCount.intValue());
            }
            CompanyUser companyUser = companyUserMapper.findByXcode(activitySuccessDTO.getFkCompanyXcode());
            if (null != companyUser) {
                activitySuccessDTO.setBindState(companyUser.getBindState());
            }
        }
        return activitySuccessDTO;
    }
    /*--------------------wx end--------------------*/

    public Integer findTeamStatusByHeadId(Long teamId) {
        return activityTeamHeadMapper.findStatusById(teamId);
    }
    /**
     * @Author: dulei
     * @Description: 返回团结束时间
     * @Date: 2017/8/25 15:12
     */
    public String findTeamEndTime(Long id) {
        ActivityHeadMsgDTO activityHeadMsgDTO = (ActivityHeadMsgDTO) activityTeamHeadMapper.findTeamMsgById(id);
        Date arriveDate = org.apache.commons.lang.time.DateUtils.addHours(activityHeadMsgDTO.getPayTime(),activityHeadMsgDTO.getTimeLimit());
        return DateUtils.getDateTimeFormat(arriveDate);
    }

    public ActivityHeadTimeDTO findTeamJoinMsg(Long teamId) {
        ActivityHeadTimeDTO activityHeadTimeDTO = new ActivityHeadTimeDTO();
        activityHeadTimeDTO.setTime(findTeamEndTime(teamId));
        if (findTeamStatusByHeadId(teamId).intValue()==3){
            //团已经成功
           List<String> list = activityOrderMapper.findJoinPhones(teamId);
            activityHeadTimeDTO.setPhones(list);
        }else {
            activityHeadTimeDTO.setPhones(new ArrayList<>());
        }
        return activityHeadTimeDTO;
    }
}
